<?php
namespace app\index\model;

use app\common\model\RemoteModel;
use app\index\controller\Llogin;
use app\index\controller\Server;
use think\Config;
use think\Db;
use think\Model;

class Logintimezone extends RemoteModel
{

    protected $connection = 'db_config_dragon';
    private $hours        = ['00', '01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23'];
    /**
     * 初始化
     *
     * @return   void
     */
    protected function initialize()
    {
        parent::initialize();
        $this->table = 'logintimezone';

        $this->llogin      = new Llogin();
        $this->lloginModel = new \app\index\model\Llogin();
        
        # 记录开服日期
        # 
        $this->server = new Server();
        $this->new_open_date = $this->server->getOpenDate();
    }

    /**
     * 列表(主键列表，条件数组，闭包查询)
     *
     * @param    array $param 查询条件
     * @return   void
     */
    public function doList($param = null)
    {

        try {

            //查询数据
            $result = self::all($param);
            $rows   = [];

            foreach ($result as $data) {
                $item = $data->getData();
                array_push($rows, $item);
            }

            //返回结果
            $res = array();

            $total = count($rows);

            if ($total > 0) {
                $res['rows']  = $rows;
                $res['total'] = $total;
            } else {
                $res['total'] = 0;
                $res['rows']  = array();
            }

            //请求类型返回
            return ($res);

        } catch (\Exception $e) {
            throw new \think\Exception('异常消息:' . $e->getMessage());
        }
    }

    /**
     * 返回数据表date最新日期
     *
     * @return int 当前id最大值
     */
    public function getRecentDate()
    {
        try {

            $res = $this->field('date')->order('date desc')->limit(1)->select();

            return $res ? $res[0]->date : null;

        } catch (\Exception $e) {
            throw new \think\Exception('异常消息:' . $e->getMessage());
        }
    }
    /**
     * Llogin表最新记录更新
     *
     * @return   void
     */
    public function updateToRecent()
    {
        $this->llogin->updateToRecent();
    }
    /**
     * 计算登录时间分布到最近日期
     *
     * @return   void
     */
    public function computeToRecent()
    {

        try {

            $yesterday = date("Y-m-d", strtotime("-1 day"));

            //开服日期或者最新日期
            //
            $recent_date = $this->getRecentDate();

            //最近日期为昨天则不用计算
            //
            if ($yesterday == $recent_date) {

                return;

            } else if (empty($recent_date)) {

                //如果为null则从开服日期开始计算
                //
                $recent_date = $this->new_open_date;
            }

            //留存计算开始日期

            $from_date = ($recent_date == $this->new_open_date) ? $recent_date : date('Y-m-d', strtotime($recent_date) + 3600 * 24);

            //留存计算终止日期

            $end_date = $yesterday;

            //起始日期到终止日期的天数

            $days = floor((strtotime($end_date) - strtotime($from_date)) / 86400);

            $rows = [];

            for ($i = 0; $i <= $days; $i++) {

                $data = [];

                //起始计算日期
                //
                $calcDate     = date("Y-m-d", (strtotime($from_date) + 3600 * 24 * $i));
                $data['date'] = $calcDate;

                foreach ($this->hours as $hour) {
                    $sql = "SELECT COUNT(DISTINCT `characterid`) AS count FROM `l_login` WHERE `status` in(1,2) AND SUBSTRING(`createtime`, 1, 10)='{$calcDate}' AND SUBSTRING(`createtime`, 12, 2)='{$hour}'";
                    //dump($sql);
                    $res = Db::query($sql);

                    $key        = 'zone_' . (int) $hour;
                    $data[$key] = $res ? $res[0]['count'] : 0;
                }
                array_push($rows, $data);
            }

            //dump($rows);die;
            $this->allowField(true)->saveAll($rows);

        } catch (\Exception $e) {
            throw new \think\Exception('异常消息:' . $e->getMessage());
        }
    }
}
